package main

import (
	"gitee.com/liukexing/mqbroker/core/driver/config"
	"gitee.com/liukexing/mqbroker/core/driver/logger"
	"gitee.com/liukexing/mqbroker/core/server"
	"gitee.com/liukexing/mqbroker/core/server/pubsub"
	"gitee.com/liukexing/mqbroker/core/typedef"
)

func main() {
	if config.CheckModule() {
		return
	}
	if server.Start() {
		return
	}
	//info := typedef.ModuleInfo{ID: "main"}
	//pubsub.CommandMsgSubClient(info, MsgReceiver)
	//pubsub.ComputeMsgSubClient(info, MsgReceiver_C)
	pubsub.Server.AddSubscriber("Log", "command", &pubsub.CommonMsgHandle{
		CustPraise: func(c *pubsub.CommonMsgHandle, v []byte) (interface{}, bool) {
			logger.Info(typedef.CommInfo{
				Message: "command::" + string(v),
			})
			return nil, true
		},
	})
	pubsub.Server.AddSubscriber("Log", "compute", &pubsub.CommonMsgHandle{
		CustPraise: func(c *pubsub.CommonMsgHandle, v []byte) (interface{}, bool) {
			logger.Info(typedef.CommInfo{
				Message: "compute::" + string(v),
			})
			return nil, true
		},
	})

	//for i := 1; i < 3; i++ {
	//	time.Sleep(time.Second)
	//	pubsub.CommandMsgPub("main", comlookupd.Config.Info.Module, "find", nil)
	//}
	//for i := 1; i < 3; i++ {
	//	time.Sleep(time.Second)
	//	pubsub.ComputeMsgPub("main", fm.ID, map[string]interface{}{"help": "test"})
	//}
	//for i := 1; i < 20; i++ {
	//	//time.Sleep(time.Second)
	//	logger.Info(typedef.CommInfo{
	//		Message: pubsub.MessageReplyClient(fm.ID, "help", map[string]interface{}{"help": "test"}, 5),
	//	})
	//}
	config.Exit = make(chan int, 1)
	<-config.Exit
	return
}

var fm typedef.ModuleInfo

func MsgReceiver(sender string, resp typedef.CommandResponse) {
	data := resp.Response["info"]
	if fm.ID == "" {
		if err := typedef.Decode(data, &fm);err !=nil{
			return
		}
	}
	logger.Info(typedef.CommInfo{
		Message: map[string]interface{}{
			"sender":   sender,
			"response": resp,
		},
	})
}

func MsgReceiver_C(sender string, resp typedef.ComputeResponse) {
	logger.Info(typedef.CommInfo{
		Message: map[string]interface{}{
			"sender":   sender,
			"response": resp,
		},
	})
}
